<?php

/**
 * Menashop
 *
 * LICENSE
 *
 * This source file is subject to the license that is bundled
 * with this project in the file LICENSE.txt
 *
 * @category   Zend
 * @package    ShipmentController
 * @copyright  Copyright (c) 2011 Menashop UA Inc. (http://www.menashop.com.ua)
 * @license    LICENSE.txt
 * @version    1.0.0
 * @since      File available since Release 1.0.0
 */

/**
 * @category   Zend
 * @package    ShipmentController
 * @copyright  Copyright (c) 2011 Menashop UA Inc. (http://www.menashop.com.ua)
 * @license    LICENSE.txt
 */
class Admin_ShipmentController extends Zend_Controller_Action
{

    /**
     * The logger
     * @var Zend_Log
     */
    protected $_logger;

    /**
     * The auth data
     * @var Zend_Auth
     */
    protected $_auth;

    /**
     * The AJAX flag
     * @var boolean
     */
    protected $_isAjax;

    /**
     * Initialize the controller
     */
    public function init()
    {
        // Get logger
        $this->_logger = Zend_Registry::get('log');

        // Set admin layout
        $this->_helper->layout()->setLayout('admin');

        // Get language from locale
        $locale = Zend_Registry::get('Zend_Locale');
        $this->view->language = $locale->getLanguage();

        // Get language ID
        $languageModel = new Admin_Model_Language();
        $this->_languageId = $languageModel->findIdByShortCode($locale->getLanguage());

        // Chect authenctication
        $this->_auth = Zend_Auth::getInstance();
        if (!$this->_auth->hasIdentity()) {
            $this->_redirect('/' . $this->view->language . '/admin/login');
        }

        // Check AJAX
        if ($this->getRequest()->isXmlHttpRequest()) {

            // If AJAX - turn of auto render
            $this->_helper->layout->disableLayout();
            $this->_helper->viewRenderer->setNoRender(true);
            $this->_isAjax = true;
        } else {

            // Get current url without language
            $this->view->currentUrl = str_replace('/' . $locale->getLanguage(), '', $this->_request->getRequestUri());

            $this->view->shopName = Zend_Registry::get('config')->shopName;
        }
    }

    /**
     * Action for index
     */
    public function indexAction()
    {
        // Check AJAX
        $isAjax = false;
        if ($this->getRequest()->isXmlHttpRequest()) {
            // If AJAX - turn of auto render
            $this->_helper->layout->disableLayout();
            $this->_helper->viewRenderer->setNoRender(true);
            $isAjax = true;
        }

        // Initialize filters for orders
        $id = null;
        $toName = null;
        $quantityFrom = null;
        $quantityTo = null;
        $costFrom = null;
        $costTo = null;
        $updatedFrom = null;
        $updatedTo = null;
        $createdFrom = null;
        $createdTo = null;
        $shipmentStatusId = null;
        $orderId = null;
        $sort = null;
        $direction = null;
        $page = 1;
        $rowCount = 20;

        // Initialize form for filter
        $form = new Admin_Model_FormShipments();
        $form->setAction('/' . $this->view->language . '/admin/shipment/index');

        // Get request params
        if ($this->getRequest()->isPost() && $form->isValid($data = $this->_request->getPost())) {
            $id = $data['id'];
            $toName = $data['to_name'];
            $quantityFrom = $data['quantity_from'];
            $quantityTo = $data['quantity_to'];
            $costFrom = $data['cost_from'];
            $costTo = $data['cost_to'];
            $updatedFrom = $data['updated_from'];
            $updatedTo = $data['updated_to'];
            $createdFrom = $data['created_from'];
            $createdTo = $data['created_to'];
            $orderId = $data['order_id'];
            $shipmentStatusId = $data['status'];
            $sort = $data['sort'];
            $direction = $data['direction'];
            $page = $data['page'];
            $rowCount = $data['rows'];
        }

        // Get orders from database
        $shipmentModel = new Admin_Model_Shipment();
        $this->view->shipments = $shipmentModel->getAllByFilter($id, $toName, $quantityFrom, $quantityTo, $costFrom, $costTo, $updatedFrom, $updatedTo, $createdFrom, $createdTo, $orderId, $shipmentStatusId, $sort, $direction, $page, $rowCount);

        // Get page count
        $recordsCount = $shipmentModel->getCountByFilter($id, $toName, $quantityFrom, $quantityTo, $costFrom, $costTo, $updatedFrom, $updatedTo, $createdFrom, $createdTo, $orderId, $shipmentStatusId);
        $form->records_count->setValue($recordsCount);
        $form->pages_count->setValue(ceil($recordsCount / $rowCount));

        // Add form to view
        $this->view->formShipments = $form;

        // Render AJAX content
        if ($isAjax) {
            echo $this->view->render('/shipment/_filtered.phtml');
        }

        // Get time of execution
        $startTime = Zend_Registry::get('startTime');
        $totalTime = round(microtime(true) - $startTime, 3);
        $this->_logger->debug(__METHOD__ . " spent $totalTime s");
    }

    /**
     * Action for edit
     */
    function editAction()
    {
        // Get order ID from request
        $orderId = $this->_request->getParam('order_id');

        // Get order from database
        $orderModel = new Admin_Model_Order();
        $order = $orderModel->getById($orderId);
        $this->view->order = $order;

        // Get customer information from database
        $customerModel = new Admin_Model_Customer();
        $customer = $customerModel->getById($order->customer_id);
        $this->view->customer = $customer;

        // Get information abount invoice from database
        $invoiceModel = new Admin_Model_Invoice();
        $invoice = $invoiceModel->getByOrderId($orderId);
        $this->view->invoice = $invoice;

        // Get information about shipment from database
        $shipmentModel = new Admin_Model_Shipment();
        $shipment = $shipmentModel->getByOrderId($orderId);

        // Initialize shipment form
        $form = new Admin_Model_FormShipment();
        $form->setAction('/' . $this->view->language . '/admin/shipment/edit/' . $orderId);
        if ($shipment) {
            $form->id->setValue($shipment->id);
            $form->quantity->setValue($shipment->quantity);
            $form->cost->setValue($shipment->cost);
            $form->to_name->setValue($shipment->to_name);
            $form->status->setValue($shipment->shipment_status_id);
        }

        // Has the shipment form been posted?
        if ($this->getRequest()->isPost()) {
            $data = $this->_request->getPost();

            // If the submitted data is valid, attempt to save shipment
            if ($form->isValid($data)) {
                $shipment = array();
                $shipment['id'] = $data['id'];
                $shipment['quantity'] = $data['quantity'];
                $shipment['cost'] = $data['cost'];
                $shipment['to_name'] = $data['to_name'];
                $shipment['shipment_status_id'] = $data['status'];
                $shipment['order_id'] = $orderId;
                $shipmentModel->save($shipment);
                $this->_redirect('/' . $this->view->language . '/admin/order/view/' . $orderId);
            } else {
                $this->view->errors = $form->getErrors();
            }
        }

        // Add form to view
        $this->view->formShipment = $form;

        // Get order products from database
        $orderProductModel = new Admin_Model_OrderProduct();
        $orderProdutcs = $orderProductModel->getPairsByOrderId($orderId);

        // Get information about order products
        $productIds = array_keys($orderProdutcs);
        $productModel = new Admin_Model_Product();
        $result = $productModel->getByIds($productIds, $this->_languageId);
        $this->view->products = $result;

        // Calculate order total and get products count for view
        $total = 0;
        $totalCount = 0;
        foreach ($result as $product) {
            $product->count = $orderProdutcs[$product->id];
            $total += $product->count * $product->price;
            $totalCount += $product->count;
        }
        $this->view->total = $total;
        $this->view->totalCount = $totalCount;

        // Get time of execution
        $startTime = Zend_Registry::get('startTime');
        $totalTime = round(microtime(true) - $startTime, 3);
        $this->_logger->debug(__METHOD__ . " spent $totalTime s");
    }

}

